const {
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()


module.exports = () => {
	return async function auth(ctx, next) {
		try {

			// 仅供调试
			if (envCfg.debug) {
				ctx.auth = {
					//注意修改此处
					loginUserId: "635ded65bf704d0001dc1532",
					tenantId: "0",
					roleCodes: ["admin"],
					authorities: [
						"sys:user:list", "sys:dict:list", 
						"sys:org:list", "sys:menu:list",
						"sys:role:list", "sys:file:list", 
						"sys:login-record:list","sys:operation-record:list",
					],
					
					
					_id: "6361103ce7f27c000171b00f",
					key: "15355fea-81cf-4c46-a987-c0a9180e079a",
					ip: "117.175.49.236",
				}
				if(!ctx.event.headers) ctx.event.headers = {}
				ctx.event.headers[envCfg.authorizationName.toLowerCase()] = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbl9zZXNzaW9uX2tleSI6IjE1MzU1ZmVhLTgxY2YtNGM0Ni1hOTg3LWMwYTkxODBlMDc5YSIsImlhdCI6MTY2NzMwNTUzMiwibmJmIjoxNjY3MzA1NTMyLCJleHAiOjE2Njc5MTAzMzIsInN1YiI6IlRva2VuIEJ1aWxkIn0.PwGOPV-DeYGVC8zEHB2GsSO2rgolYZ6gwlnfFatkkk7a1EKHKK3Is9gYVU-dv0Oxjyt11f2zjlMYRWwn6ewIPqQKxHbKHOHUsdi_bb3vjjenLC2SU7-RrbFU2ZUMkBt4SJXRwpkXP-qREAPQRUZTOc-i_ncw7zcY-SQHwR57dqRKIF-oty7g53M9q0a7sCqq8lMH4o5Yr2yriFIubMI_AcOLbCQTmuKHMTNxbqO0kKVwqWgX4xCyUmtDL6_co77D7hTYO9popw6AITEzL1tnMF5bMETzRYh8DehNpTkXdJphoMGf568OkiQOEsXJVYZLRMlPL7Xtcjhh5Qtc3-qZIg";
				await next();
				return
			}

			const dbJQL = ctx.event.dbJQL;
			dbJQL.setUser({
				role: ['admin']
			})
			// 校验token
			var vt = await verify_token(ctx.event.headers[envCfg.authorizationName.toLowerCase()]);
			if (vt.code !== 0) throw {
				code: 401,
				message: 'middleware：' + vt.message
			};
			// 有新token
			if (vt.newToken) ctx.headers[envCfg.authorizationName.toLowerCase()] = vt.newToken;
			// auth
			if (!ctx.auth) {
				var login_session_key = vt.payload.login_session_key;
				try {
					var result = await dbJQL.collection("mh-sys-loginsession")
						.where({
							key: login_session_key
						})
						.get({
							getOne: true
						})
					ctx.auth = result.data;
					await next();

				} catch (e) {
					throw {
						code: 500,
						message: e.errMsg
					};
				}
			} else {
				await next();
			}
		} catch (e) {
			console.log("中间件错误：")
			console.log(e)
			await next();
		}
	};
}
